﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using DevelopTool.Bll.DbBlls;
using DevelopTool.Common;
using DevelopTool.Forms.CommonControls.CodeEditor;
using DevelopTool.Forms.CommonForms;
using DevelopTool.Forms.CommonHelpers;
using DevelopTool.Model;
using DevelopTool.Model.CommonModels;
using DevelopTool.Model.DbModels;
using Sunny.UI;

namespace DevelopTool.Forms.CommonControls
{
    /// <summary>
    /// 数据展示自定义控件
    /// </summary>
    public partial class DataDisplayControl : UIUserControl
    {
        #region 事件

        public delegate void DataGridViewCellClickHandler(DataGridViewEventArgs dataGridViewEventArgs);

        /// <summary>
        /// DataGridView单元格单击事件
        /// </summary>
        [Description("DataGridView单元格单击事件"), Category("DevelopTool")]
        public event DataGridViewCellClickHandler DataGridViewCellClick;

        /// <summary>
        /// DataGridView单元格双击事件
        /// </summary>
        [Description("DataGridView单元格双击事件"), Category("DevelopTool")]
        public event DataGridViewCellClickHandler DataGridViewCellDoubleClick;


        /// <summary>
        /// 数据刷新事件
        /// </summary>
        [Description("数据刷新事件"), Category("DevelopTool")]
        public event EventHandler DataReLoad;

        #endregion 事件


        #region 公有属性

        private string _titleText = "";

        public string TitleText
        {
            get
            {
                return this._titleText;
            }
            set
            {
                this._titleText = value;
                this.SetTitleText(value);
            }
        }

        private bool _showReloadToolStripItem = true;

        /// <summary>
        /// 是否显示数据刷新右键菜单项
        /// </summary>
        [Description("是否显示数据刷新右键菜单项")]
        [DefaultValue(value: true)]
        [Category("DevelopTool")]
        public bool ShowReloadToolStripItem
        {
            get
            {
                return this._showReloadToolStripItem;
            }
            set
            {
                this._showReloadToolStripItem = value;
                this.刷新数据ToolStripMenuItem.Visible = value;
                this.toolStripSeparator6.Visible = value;
            }
        }

        private bool _showTopPanl = true;

        /// <summary>
        /// 是否显示顶部搜索容器
        /// </summary>
        [Description("是否显示顶部搜索容器")]
        [DefaultValue(value: true)]
        [Category("DevelopTool")]
        public bool ShowTopPanl
        {
            get
            {
                return this._showTopPanl;
            }
            set
            {
                this._showTopPanl = value;
                this.pnlTop.Visible = value;
            }
        }


        private bool _showTopSearhTextBox = true;

        /// <summary>
        /// 是否显示顶部搜索输入框
        /// </summary>
        [Description("是否显示顶部搜索输入框")]
        [DefaultValue(value: true)]
        [Category("DevelopTool")]
        public bool ShowTopSearhTextBox
        {
            get
            {
                return this._showTopSearhTextBox;
            }
            set
            {
                this._showTopSearhTextBox = value;
                this.TextBoxKeyword.Visible = value;

                if(!value)
                {
                    this.pnlTop.Height = 25;
                }
                else
                {
                    this.pnlTop.Height = 55;
                }
            }
        }

        private bool _showTopPanlTitle = true;

        /// <summary>
        /// 是否显示顶部搜索块标题
        /// </summary>
        [Description("是否显示顶部搜索块标题")]
        [DefaultValue(value: true)]
        [Category("DevelopTool")]
        public bool ShowTopPanlTitle
        {
            get
            {
                return this._showTopPanlTitle;
            }
            set
            {
                this._showTopPanlTitle = value;
                if(value)
                {
                    this.pnlTop.Height = 55;
                    this.pnlTop.Padding = new Padding(0,20,0,0);
                }
                else
                {
                    this.pnlTop.Height = 35;
                    this.pnlTop.Padding = new Padding(0,0,0,0);
                }
            }
        }

        private bool _showDataGridViewFooter = true;

        /// <summary>
        /// 是否显示DataGridView底部统计
        /// </summary>
        [Description("是否显示DataGridView底部统计")]
        [DefaultValue(value: true)]
        [Category("DevelopTool")]
        public bool ShowDataGridViewFooter
        {
            get
            {
                return this._showDataGridViewFooter;
            }
            set
            {
                this._showDataGridViewFooter = value;
                this.dataGridViewFooter.Visible = value;
            }
        }


        private Orientation _splitContainerOrientation = Orientation.Horizontal;

        /// <summary>
        /// 分隔栏方向
        /// </summary>
        [Description("分隔栏方向")]
        [DefaultValue(value: Orientation.Horizontal)]
        [Category("DevelopTool")]
        public Orientation SplitContainerOrientation
        {
            get
            {
                return this._splitContainerOrientation;
            }
            set
            {
                this._splitContainerOrientation = value;
                this.uiSplitContainer.Orientation = value;
            }
        }


        /// <summary>
        /// 连接信息
        /// </summary>
        private DbInfo dbInfo;

        /// <summary>
        /// 连接信息
        /// </summary>
        public DbInfo DbInfo
        {
            get
            {
                return this.dbInfo;
            }
            set
            {
                this.dbInfo = value;
                SetTitleText(null);
            }
        }

        /// <summary>
        /// 当前选择的行
        /// </summary>
        private DataGridViewRow selectedRow;
        /// <summary>
        /// 当前选择的行
        /// </summary>
        public DataGridViewRow SelectedRow
        {
            get
            {
                return this.selectedRow;
            }
            set
            {
                this.selectedRow = value;
            }
        }

        /// <summary>
        /// 当前选择的单元格
        /// </summary>
        private DataGridViewCell selectedCell;
        /// <summary>
        /// 当前选择的单元格
        /// </summary>
        public DataGridViewCell SelectedCell
        {
            get
            {
                return this.selectedCell;
            }
            set
            {
                this.selectedCell = value;
            }
        }

        /// <summary>
        /// 当前选择的列
        /// </summary>
        private DataGridViewColumn selectedColumn;
        /// <summary>
        /// 当前选择的列
        /// </summary>
        public DataGridViewColumn SelectedColumn
        {
            get
            {
                return this.selectedColumn;
            }
            set
            {
                this.selectedColumn = value;
            }
        }


        /// <summary>
        /// 当前选择行的键值集合
        /// </summary>
        private Dictionary<string,string> selectedRowDic = new Dictionary<string,string>();
        /// <summary>
        /// 当前选择行的键值集合
        /// </summary>
        public Dictionary<string,string> SelectedRowDic
        {
            get
            {
                return this.selectedRowDic;
            }
            set
            {
                this.selectedRowDic = value;
            }
        }

        /// <summary>
        /// DataGridView控件
        /// </summary>
        public UIDataGridView DataGridView
        {
            get
            {
                return this.dataGridView;
            }
        }

        /// <summary>
        /// 进度条控件
        /// </summary>
        public UIProcessBar ProcessBar
        {
            get
            {
                return this.uiProcessBar;
            }
        }

        /// <summary>
        /// TextEditorForm控件
        /// </summary>
        public CodeEditorControl CodeEditorControl
        {
            get
            {
                return this.codeEditorControl;
            }
        }

        /// <summary>
        /// DataGridView底部统计控件
        /// </summary>
        public UIDataGridViewFooter DataGridViewFooter
        {
            get
            {
                return this.dataGridViewFooter;
            }
        }


        /// <summary>
        /// 需要固定的首行列名
        /// </summary>
        private string _fixedFirstRowColumnName = string.Empty;

        #endregion 公有属性


        #region 私有字段

        /// <summary>
        /// 展示的数据
        /// </summary>
        private DataTable dataTable;

        private string sortStr;

        private List<DataGridColumn> dataGridColumns;

        /// <summary>
        /// DataGridView筛选下拉框
        /// </summary>
        private DataGridViewFilterForm dgvFilterForm;


        private UIContextMenuStrip bindContextMenuStrip;

        #endregion 私有字段


        public DataDisplayControl()
        {
            InitializeComponent();
        }

        private void DataDisplayControl_Load(object sender,EventArgs e)
        {
            #region DataGridView样式设置
            this.dataGridView.EnableHeadersVisualStyles = false;
            this.dataGridView.ShowCellToolTips = false;
            this.dataGridView.AllowUserToAddRows = false;
            // dgv.AllowUserToDeleteRows = false;
            this.dataGridView.AllowUserToOrderColumns = true;
            //  dgv.EnableHeadersVisualStyles = false;
            this.dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
            this.dataGridView.RowHeadersVisible = true;

            this.dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;

            #endregion DataGridView样式设置

            this.uiSplitContainer.SplitterDistance = Convert.ToInt32(this.Height * 0.6);//设置DataGridViewRow的高度

            if(string.IsNullOrEmpty(this._titleText))
                SetTitleText(this.ParentForm?.Text);
        }


        /// <summary>
        /// 设置标题文字
        /// </summary>
        /// <param name="text"></param>
        public void SetTitleText(string text)
        {
            if(!string.IsNullOrEmpty(text))
            {
                this.pnlTop.Text = text;
            }
            else if(this.dbInfo != null)
            {
                string dataBaseStr = string.IsNullOrEmpty(this.dbInfo.DataBase) ? string.Empty : $" 实例：{this.dbInfo.DataBase}";

                if(!string.IsNullOrEmpty(this.dbInfo.ConnectionString))
                {
                    DbInfo info = new DbInfoBll().GetDbInfoByConnectionString(this.dbInfo.ConnectionString);

                    this.pnlTop.Text = $"连接：{this.dbInfo.NodeName}  用户：{info.UserName}  地址：{info.Ip} {dataBaseStr}";
                }
                else
                {
                    this.pnlTop.Text = $"连接：{this.dbInfo.NodeName}  用户：{this.dbInfo.UserName}  地址：{this.dbInfo.Ip} {dataBaseStr}";
                }
            }
        }


        /// <summary>
        /// 绑定数据
        /// </summary>
        /// <param name="dataTable">DataTable数据</param>
        /// <param name="dataGridColumns">列信息集合</param>
        /// <param name="sortStr">排序</param>
        /// <param name="dbInfo">数据库连接信息</param>
        public void BindData(DataTable dataTable,List<DataGridColumn> dataGridColumns = null,string sortStr = "")
        {
            this.dataTable = dataTable;
            this.dataGridColumns = dataGridColumns;
            this.sortStr = sortStr;

            this.dataGridView.DataSource = DataGridViewHelper.BindingSource(dataTable,sortStr: sortStr);//绑定数据到DataGridView

            this.dgvFilterForm = new DataGridViewFilterForm(this,dataGridView.Columns);

            SetDataGridViewFooter();

            DataGridViewHelper.SetDataGridViewColumnWidth(this.dataGridView,dataGridColumns);
        }


        /// <summary>
        /// 设置DataGridView底部合计
        /// </summary>
        private void SetDataGridViewFooter()
        {
            if(this.dataGridView.Rows.Count <= 0 || this.dataGridView.Columns.Count <= 0)
            {
                dataGridViewFooter.Visible = false;
                return;
            }
            else
            {
                dataGridViewFooter.Visible = true;
            }

            dataGridViewFooter.Clear();
            if(this.dataGridView.Columns.Count == 1)
            {
                //如果只有一列，就特殊处理下
                dataGridViewFooter[this.dataGridView.Columns[0].Name] = "总行数" + this.dataGridView.Rows.Count.ToString();
            }
            else
            {
                dataGridViewFooter[this.dataGridView.Columns[0].Name] = "总行数";
                dataGridViewFooter[this.dataGridView.Columns[1].Name] = this.dataGridView.Rows.Count.ToString();
            }
        }

        private void dataGridView_RowsAdded(object sender,DataGridViewRowsAddedEventArgs e)
        {
            this.SetDataGridViewFooter();
        }

        private void dataGridView_RowsRemoved(object sender,DataGridViewRowsRemovedEventArgs e)
        {
            this.SetDataGridViewFooter();
        }

        #region 搜索相关

        /// <summary>
        /// 外部调用搜索
        /// </summary>
        /// <param name="keywordText"></param>
        public void Search(string keywordText)
        {
            this.TextBoxKeyword.Text = keywordText;
        }


        /// <summary>
        /// 搜索框文本改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBoxKeyword_TextChanged(object sender,EventArgs e)
        {
            if(dgvFilterForm != null)
                this.dataGridView.DataSource = DataGridViewHelper.BindingSource(this.dataTable,this.dgvFilterForm.GetFilter(this.TextBoxKeyword.Text),this.sortStr);
        }


        /// <summary>
        /// 搜索框按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBoxKeyword_ButtonClick(object sender,EventArgs e)
        {
            if(dgvFilterForm != null)
                dgvFilterForm.ShowForm(this.TextBoxKeyword);
        }

        #endregion 搜索相关


        #region dataGridView相关

        /// <summary>
        /// 添加序号列
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView_RowPostPaint(object sender,DataGridViewRowPostPaintEventArgs e)
        {
            DataGridViewHelper.AddColumnHeader(this.dataGridView,e);
        }

        /// <summary>
        /// 绑定列头属性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView_DataSourceChanged(object sender,EventArgs e)
        {
            DataGridViewHelper.SetDataGridViewColumnInfo(this.dataGridView,this.dataGridColumns);
        }

        /// <summary>
        /// 单元格单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView_CellMouseDown(object sender,DataGridViewCellMouseEventArgs e)
        {
            if(e.Button == MouseButtons.Right)//判断点的是不是右键
            {
                dataGridView.ContextMenuStrip = null;//绑定前先清空下右键菜单
                if(e.RowIndex < 0 || e.ColumnIndex < 0) return;

                var row = dataGridView.Rows[e.RowIndex];//右键选定的行             
                var cell = row.Cells[e.ColumnIndex];//右键选定的单元格
                DataGridViewColumn headColumn = cell.OwningColumn;

                this.selectedRowDic = new Dictionary<string,string>();
                foreach(DataGridViewCell dataGridViewCell in row.Cells)
                {
                    this.selectedRowDic.Add(dataGridViewCell.OwningColumn.Name,dataGridViewCell.Value.ToString());
                }

                this.selectedRow = row;
                this.selectedColumn = cell.OwningColumn;
                this.selectedCell = cell;

                var args = new DataGridViewEventArgs() { MouseButton = MouseButtons.Right,Column = headColumn,Row = row,Cell = cell };
                DataGridViewCellClick?.Invoke(args);
                if(args.Cancel) return;

                //若单元格已是选中状态就不再进行设置
                if(cell.Selected == false)
                {
                    dataGridView.ClearSelection();
                    cell.Selected = true;
                }

                if(this.dataGridColumns != null && this.dataGridColumns.Count > 0)
                {
                    DataGridColumn dataGridColumn = this.dataGridColumns.FirstOrDefault(it => it.ColumnType.HasFlag(ColumnType.RowMain));
                    if(dataGridColumn != null)
                    {
                        if(this.dataGridView.Columns.Cast<DataGridViewColumn>().Any(it => it.Name == dataGridColumn.ColumnName) && row.Cells[dataGridColumn.ColumnName].Value != null && !row.Cells[dataGridColumn.ColumnName].Value.ToString().IsEmpty())
                        {
                            this.行头名称ToolStripMenuItem.Visible = true;
                            string rowMainText = row.Cells[dataGridColumn.ColumnName].Value.ToString();
                            行头名称ToolStripMenuItem.Text = rowMainText;
                        }
                        else
                        {
                            this.行头名称ToolStripMenuItem.Visible = false;
                        }
                    }
                }

                dataGridView.ContextMenuStrip = this.contextMenuStripDgv;//弹出右键操作菜单                   

            }
        }


        /// <summary>
        /// 固定首行文本
        /// </summary>
        /// <param name="fixedFirstRowColumnName">需要固定文本的列名</param>
        public void FixedFirstRowText(string fixedFirstRowColumnName)
        {
            this._fixedFirstRowColumnName = fixedFirstRowColumnName;

            if(string.IsNullOrEmpty(fixedFirstRowColumnName)) return;

            if(this.dataGridView.Rows.Count <= 0) return;

            DataGridViewRow row = this.dataGridView.Rows[0];

            DataGridViewCell cell = row.Cells[fixedFirstRowColumnName];

            if(cell == null) return;
            if(cell.Value == null || string.IsNullOrEmpty(cell.Value.ToString())) return;


            DataGridViewColumn headColumn = cell.OwningColumn;

            if(headColumn.Tag is DataGridColumn gridColumn)
            {

                this.ShowCodeEditor(row,cell,gridColumn);

                foreach(DataGridViewCell c in row.Cells)
                {
                    c.Selected = c.OwningColumn.Name == fixedFirstRowColumnName;
                }

                this.uiSplitContainer.SplitterDistance = Convert.ToInt32(this.Height * 0.15);//设置DataGridViewRow的高度
            }
        }


        /// <summary>
        /// 单元格单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView_CellMouseClick(object sender,DataGridViewCellMouseEventArgs e)
        {
            if(e.Button == MouseButtons.Left)//判断点的是不是左键
            {
                try
                {
                    if(e.RowIndex < 0 || e.ColumnIndex < 0) return;
                    DataGridViewRow row = this.dataGridView.Rows[e.RowIndex];//选定的行             
                    DataGridViewCell cell = row.Cells[e.ColumnIndex];//选定的单元格
                    DataGridViewColumn headColumn = cell.OwningColumn;

                    this.selectedRowDic = new Dictionary<string,string>();
                    foreach(DataGridViewCell dataGridViewCell in row.Cells)
                    {
                        this.selectedRowDic.Add(dataGridViewCell.OwningColumn.Name,dataGridViewCell.Value.ToString());
                    }

                    this.selectedRow = row;
                    this.selectedColumn = cell.OwningColumn;
                    this.selectedCell = cell;

                    var args = new DataGridViewEventArgs() { MouseButton = MouseButtons.Left,Column = headColumn,Row = row,Cell = cell };
                    DataGridViewCellClick?.Invoke(args);
                    if(args.Cancel) return;

                    if(cell.Value == null) return;

                    if(string.IsNullOrEmpty(this._fixedFirstRowColumnName))
                    {
                        if(!(headColumn.Tag is DataGridColumn gridColumn) || !gridColumn.ColumnType.HasFlag(ColumnType.LongText) || cell.Value.IsEmpty() || cell.Value.ToString().Length <= gridColumn.ShowFormProperty.ShowTextLength)
                        {
                            this.uiSplitContainer.Panel2Collapsed = true;
                        }
                        else
                        {
                            this.ShowCodeEditor(row,cell,gridColumn);
                        }
                    }
                    else
                    {
                        if(headColumn.Tag is DataGridColumn gridColumn)
                        {
                            this.ShowCodeEditor(row,cell,gridColumn);
                        }
                    }

                }
                catch(Exception ex)
                {
                    UINotifierHelper.ShowNotifier("加载文本编辑器失败，请重试，" + ex.Message,UINotifierType.ERROR,UIStyles.CurrentResources.ErrorTitle,true,2000);
                    LogHelper.WriteErrLog(ex);
                }
            }
        }


        /// <summary>
        /// 显示编辑器控件
        /// </summary>
        /// <param name="row"></param>
        /// <param name="cell"></param>
        /// <param name="gridColumn"></param>
        public void ShowCodeEditor(DataGridViewRow row,DataGridViewCell cell,DataGridColumn gridColumn)
        {
            this.uiSplitContainer.Panel2Collapsed = false;

            #region 取编辑器标题

            string base_Name = "代码编辑器";
            if(gridColumn.ShowFormProperty != null && !gridColumn.ShowFormProperty.BaseNameColumn.IsEmpty())
            {
                //凑合一下~
                if(this.dataGridView.Columns.Cast<DataGridViewColumn>().Any(it => it.Name == gridColumn.ShowFormProperty.BaseNameColumn))
                    base_Name = row.Cells[gridColumn.ShowFormProperty.BaseNameColumn].Value.ToString();
                else
                    base_Name = row.Cells[0].Value.ToString();
            }
            else if(this.dataGridColumns != null && this.dataGridColumns.Count > 0)
            {
                DataGridColumn dataGridColumn = this.dataGridColumns.FirstOrDefault(it => it.ColumnType.HasFlag(ColumnType.RowMain));
                if(dataGridColumn != null)
                    base_Name = row.Cells[dataGridColumn.ColumnName].Value.ToString();
            }
            #endregion 取编辑器标题

            this.codeEditorControl.ContentText = cell.Value.ToString();
            this.codeEditorControl.ContentType = gridColumn.ShowFormProperty?.TextType;
            this.codeEditorControl.PanelTitle = base_Name;
            this.codeEditorControl.EnabledOpenFile = false;
        }


        /// <summary>
        /// dataGridView双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView_CellMouseDoubleClick(object sender,DataGridViewCellMouseEventArgs e)
        {
            if(e.RowIndex < 0 || e.ColumnIndex < 0) return;
            var row = this.dataGridView.Rows[e.RowIndex];//选定的行             
            var cell = row.Cells[e.ColumnIndex];//选定的单元格
            DataGridViewColumn headColumn = cell.OwningColumn;

            this.selectedRowDic = new Dictionary<string,string>();
            foreach(DataGridViewCell dataGridViewCell in row.Cells)
            {
                this.selectedRowDic.Add(dataGridViewCell.OwningColumn.Name,dataGridViewCell.Value.ToString());
            }

            this.selectedRow = row;
            this.selectedColumn = cell.OwningColumn;
            this.selectedCell = cell;

            var args = new DataGridViewEventArgs() { MouseButton = e.Button,Column = headColumn,Row = row,Cell = cell };
            DataGridViewCellDoubleClick?.Invoke(args);
            if(args.Cancel) return;
        }

        #endregion dataGridView相关


        #region 外部右键菜单相关

        /// <summary>
        /// 绑定外部右键菜单
        /// </summary>
        /// <param name="contextMenuStrip"></param>
        public void BindContextMenuStrip(UIContextMenuStrip contextMenuStrip)
        {
            if(contextMenuStrip == null) return;

            this.bindContextMenuStrip = contextMenuStrip;

            for(int i = 0 ; i < contextMenuStrip.Items.Count ; i++)
            {
                ToolStripItem toolStripItem = contextMenuStrip.Items[i];

                if(toolStripItem is ToolStripMenuItem toolStrip)
                {
                    ToolStripMenuItem newToolStripMenuItem = new ToolStripMenuItem()
                    {
                        Name = toolStripItem.Name,
                        Text = toolStripItem.Text,
                    };
                    BindToolStripDropDownItems(toolStrip,newToolStripMenuItem);

                    newToolStripMenuItem.Click += this.NewToolStripMenuItem_Click;

                    this.contextMenuStripDgv.Items.Add(newToolStripMenuItem);
                }

                else if(toolStripItem.GetType().Equals(typeof(ToolStripSeparator)))
                {
                    this.contextMenuStripDgv.Items.Add(new ToolStripSeparator());
                }
            }
        }


        /// <summary>
        /// 递归绑定外部右键菜单的子项
        /// </summary>
        /// <param name="toolStrip"></param>
        /// <param name="newToolStripMenuItem"></param>
        private void BindToolStripDropDownItems(ToolStripMenuItem toolStrip,ToolStripMenuItem newToolStripMenuItem)
        {
            foreach(ToolStripMenuItem item in toolStrip.DropDownItems)
            {
                ToolStripMenuItem newToolStripMenuItem2 = new ToolStripMenuItem()
                {
                    Name = item.Name,
                    Text = item.Text,
                };

                newToolStripMenuItem2.Click += this.NewToolStripMenuItem_Click;

                newToolStripMenuItem.DropDownItems.Add(newToolStripMenuItem2);

                if(item.HasDropDownItems)
                    BindToolStripDropDownItems(item,newToolStripMenuItem2);
            }
        }

        /// <summary>
        /// 外部右键菜单项的点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NewToolStripMenuItem_Click(object sender,EventArgs e)
        {
            if(sender is ToolStripMenuItem toolStripItem)
            {
                if(this.bindContextMenuStrip == null) return;

                for(int i = 0 ; i < this.bindContextMenuStrip.Items.Count ; i++)
                {
                    ToolStripItem toolStrip = this.bindContextMenuStrip.Items[i];

                    if(toolStrip.Name == toolStripItem.Name && toolStrip.Text == toolStripItem.Text)
                    {
                        toolStrip.PerformClick();

                        break;
                    }
                    else if(toolStrip is ToolStripMenuItem menuItem)
                    {
                        ToolStripMenuItem subToolStripItem = GetSubToolStripItem(menuItem,toolStripItem.Name);
                        if(subToolStripItem != null)
                        {
                            subToolStripItem.PerformClick();
                            break;
                        }
                    }
                }
            }

        }

        /// <summary>
        /// 按名称Name获取右键菜单的子项
        /// </summary>
        /// <param name="ctrl"></param>
        /// <param name="childName"></param>
        /// <returns></returns>
        private ToolStripMenuItem GetSubToolStripItem(ToolStripMenuItem ctrl,string childName)
        {
            if(ctrl == null) return null;
            if(ctrl.Name == childName) return ctrl;

            if(ctrl.DropDownItems.Count == 0)
            {
                return null;
            }
            else
            {
                return (from ToolStripMenuItem subCtrl in ctrl.DropDownItems.Cast<ToolStripMenuItem>() select GetSubToolStripItem(subCtrl,childName)).FirstOrDefault(tb => tb != null);
            }
        }

        #endregion 外部右键菜单相关


        #region 本地右键菜单

        private void 行头名称ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            Clipboard.SetText(this.行头名称ToolStripMenuItem.Text);
            UINotifierHelper.ShowNotifier($"已复制行头名称",UINotifierType.INFO,UIStyles.CurrentResources.InfoTitle,false,2000);
        }

        private void 复制标题ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            DataGridViewHelper.CopyDataGridViewTitleText(this.dataGridView);
            UINotifierHelper.ShowNotifier($"已复制标题",UINotifierType.INFO,UIStyles.CurrentResources.InfoTitle,false,2000);
        }

        private void 选定内容保存到笔记ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            NoteHelper.SaveToNote(this.dataGridView);
        }

        private void 选定内容推送到飞书ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            MsgHelper.SendMsg(this.dataGridView);
        }


        #region 导出数据到Excel

        private void 原始数据DataTableToExcelToolStripMenuItem_Click(object sender,EventArgs e)
        {
            ExportHelper.ExportDataToExcel(this.dataTable,"原始数据");
        }

        private void 界面数据DataGridViewToExcelToolStripMenuItem_Click(object sender,EventArgs e)
        {
            ExportHelper.ExportDataToExcel(dataGridView.ToDataTable(),"界面数据");
        }

        #endregion 导出数据到Excel


        #region 导出数据到Json

        private void 原始数据DataTableToJsonToolStripMenuItem_Click(object sender,EventArgs e)
        {
            ExportHelper.ExportDataToJSON(this.dataTable,"原始数据");
        }

        private void 界面数据DataGridViewToJsonToolStripMenuItem_Click(object sender,EventArgs e)
        {
            ExportHelper.ExportDataToJSON(dataGridView.ToDataTable(),"界面数据");
        }

        #endregion 导出数据到Json


        #region 保存为离线数据

        private void 原始数据DataTableToolStripMenuItem2_Click(object sender,EventArgs e)
        {
            OffLineHelper.SaveToOffLine(this.dataTable,null);
        }

        private void 界面数据DataGridViewToolStripMenuItem2_Click(object sender,EventArgs e)
        {
            OffLineHelper.SaveToOffLine(dataGridView.ToDataTable(),this.dataGridColumns);
        }

        #endregion 保存为离线数据


        #region 编辑器显示选择列的内容


        private void 在编辑器显示选择列的内容ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            if(sender is ToolStripMenuItem toolStripMenuItem)
            {
                if(toolStripMenuItem.Checked)//已选中
                {
                    foreach(DataGridViewCell cell in dataGridView.SelectedCells)
                    {
                        DataGridViewColumn headColumn = cell.OwningColumn;
                        if(headColumn.Tag != null && headColumn.Tag is DataGridColumn gridColumn)
                        {
                            gridColumn.ColumnType &= ~ColumnType.LongText;
                        }
                    }
                    this.在编辑器显示选择列的内容ToolStripMenuItem.Checked = false;
                }
                else//未选中
                {
                    foreach(DataGridViewCell cell in dataGridView.SelectedCells)
                    {
                        DataGridViewColumn headColumn = cell.OwningColumn;
                        if(headColumn.Tag != null && headColumn.Tag is DataGridColumn gridColumn)
                        {
                            gridColumn.ColumnType |= ColumnType.LongText;

                            if(gridColumn.ShowFormProperty == null)
                                gridColumn.ShowFormProperty = new ShowFormProperty();
                        }
                        else
                        {
                            gridColumn = new DataGridColumn(headColumn.HeaderText)
                            {
                                ColumnText = headColumn.HeaderText,
                                ShowFormProperty = new ShowFormProperty()
                                {
                                    TextType = "Text"
                                }
                            };
                            gridColumn.ColumnType |= ColumnType.LongText;

                        }
                        headColumn.Tag = gridColumn;
                    }
                    this.在编辑器显示选择列的内容ToolStripMenuItem.Checked = true;
                }
            }
        }

        #endregion 编辑器显示选择列的内容


        /// <summary>
        /// 右键菜单打开时事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void contextMenuStripDgv_Opened(object sender,EventArgs e)
        {
            foreach(DataGridViewCell cell in dataGridView.SelectedCells)
            {
                DataGridViewColumn headColumn = cell.OwningColumn;
                if(headColumn.Tag != null && headColumn.Tag is DataGridColumn gridColumn)
                {
                    this.在编辑器显示选择列的内容ToolStripMenuItem.Checked = gridColumn.ColumnType.HasFlag(ColumnType.LongText);
                }
            }
        }


        private void 刷新数据ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            this.DataReLoad?.Invoke(this,EventArgs.Empty);
        }

        #endregion 本地右键菜单

        private void dataGridView_SizeChanged(object sender,EventArgs e)
        {
            DataGridViewHelper.SetDataGridViewColumnWidth(this.dataGridView,this.dataGridColumns);
        }

    }
}
